/**
 * 校园二手交易平台 - Mock数据工具
 * 提供模拟数据的生成、管理、清理和重置功能
 */

import { Product, ProductCategory, ProductCondition, ProductStatus, TransactionMethod } from '../types/product';

/**
 * Mock数据管理工具类
 */
export class MockDataUtils {
  private static mockDataStorage = new Map<string, any>();
  
  /**
   * 生成指定数量的商品数据
   */
  static generateProducts(count: number = 150): Product[] {
    const products: Product[] = [];
    
    // 价格区间配置
    const priceRanges = {
      [ProductCategory.TEXTBOOKS]: { min: 15, max: 120 },
      [ProductCategory.ELECTRONICS]: { min: 200, max: 5000 },
      [ProductCategory.CLOTHING]: { min: 30, max: 300 },
      [ProductCategory.DAILY_GOODS]: { min: 20, max: 200 },
      [ProductCategory.SPORTS]: { min: 40, max: 400 },
      [ProductCategory.STATIONERY]: { min: 10, max: 100 },
      [ProductCategory.DORMITORY]: { min: 50, max: 300 },
      [ProductCategory.OTHER]: { min: 20, max: 200 }
    };
    
    // 商品状态分布
    const statusWeights = {
      [ProductStatus.ACTIVE]: 0.7,  // 70% 上架中
      [ProductStatus.SOLD]: 0.2,    // 20% 已售出
      [ProductStatus.INACTIVE]: 0.1 // 10% 已下架
    };
    
    for (let i = 1; i <= count; i++) {
      const category = this.getRandomCategory();
      const priceRange = priceRanges[category];
      const basePrice = Math.floor(Math.random() * (priceRange.max - priceRange.min)) + priceRange.min;
      
      const product: Product = {
        id: `mock_product_${Date.now()}_${i}`,
        title: this.generateProductTitle(category, i),
        description: this.generateProductDescription(category),
        price: this.calculateAdjustedPrice(basePrice, this.getRandomCondition()),
        originalPrice: Math.floor(basePrice * (1 + Math.random() * 0.5)),
        category,
        condition: this.getRandomCondition(),
        transactionMethod: this.getRandomTransactionMethod(),
        images: this.generateProductImages(i),
        location: this.generateLocation(),
        publisher: this.generatePublisher(),
        publishedAt: this.generateRandomDate(),
        updatedAt: new Date(),
        status: this.getWeightedRandomStatus(statusWeights),
        viewCount: Math.floor(Math.random() * 500),
        favoriteCount: Math.floor(Math.random() * 50),
        inquiryCount: Math.floor(Math.random() * 20),
        tags: this.generateTags(category),
        isNegotiable: Math.random() > 0.4,
        isFreeShipping: Math.random() > 0.7,
        shippingFee: Math.random() > 0.7 ? Math.floor(Math.random() * 15) + 5 : undefined,
        stock: this.generateStock(),
        isReturnable: Math.random() > 0.8,
      };
      
      products.push(product);
    }
    
    return products;
  }
  
  /**
   * 获取随机商品类别
   */
  private static getRandomCategory(): ProductCategory {
    const categories = Object.values(ProductCategory);
    return categories[Math.floor(Math.random() * categories.length)];
  }
  
  /**
   * 获取随机新旧程度
   */
  private static getRandomCondition(): Product['condition'] {
    const conditions = [ProductCondition.NEW, ProductCondition.LIKE_NEW, ProductCondition.VERY_GOOD, ProductCondition.GOOD, ProductCondition.FAIR, ProductCondition.POOR];
    return conditions[Math.floor(Math.random() * conditions.length)];
  }
  
  /**
   * 获取随机交易方式
   */
  private static getRandomTransactionMethod(): Product['transactionMethod'] {
    const methods = [TransactionMethod.FACE_TO_FACE, TransactionMethod.MAIL, TransactionMethod.BOTH];
    return methods[Math.floor(Math.random() * methods.length)];
  }
  
  /**
   * 根据权重获取随机状态
   */
  private static getWeightedRandomStatus(weights: Record<string, number>): ProductStatus {
    const random = Math.random();
    let cumulative = 0;
    
    for (const [status, weight] of Object.entries(weights)) {
      cumulative += weight;
      if (random <= cumulative) {
        return status as ProductStatus;
      }
    }
    
    return ProductStatus.ACTIVE; // 默认值
  }
  
  /**
   * 生成商品标题
   */
  private static generateProductTitle(category: ProductCategory, index: number): string {
    const titles = {
      [ProductCategory.TEXTBOOKS]: [
        '高等数学教材', '英语四级词汇', '计算机程序设计', '经济学原理',
        '大学物理实验', '线性代数', '数据结构', '操作系统', '计算机网络'
      ],
      [ProductCategory.ELECTRONICS]: [
        '笔记本电脑', '智能手机', '蓝牙耳机', '平板电脑', '数码相机',
        '游戏主机', '智能手表', '充电宝', '键盘鼠标'
      ],
      [ProductCategory.CLOTHING]: [
        '运动外套', '休闲卫衣', '牛仔裤', '运动鞋', '羽绒服',
        'T恤衫', '休闲裤', '帆布鞋', '毛衣'
      ],
      [ProductCategory.DAILY_GOODS]: [
        '保温杯', '台灯', '收纳箱', '电热水壶', '小风扇',
        '床上用品', '洗漱用品', '餐具', '镜子'
      ],
      [ProductCategory.SPORTS]: [
        '篮球', '羽毛球拍', '瑜伽垫', '跑步鞋', '健身器材',
        '运动服', '护具', '网球拍', '跳绳'
      ],
      [ProductCategory.STATIONERY]: [
        '笔记本', '中性笔', '计算器', '文件夹', '书包',
        '尺子', '橡皮', '修正带', '荧光笔'
      ],
      [ProductCategory.DORMITORY]: [
        '床垫', '书桌', '衣柜', '电风扇', '台灯',
        '收纳柜', '椅子', '窗帘', '床上桌'
      ],
      [ProductCategory.OTHER]: [
        '闲置物品', '手工艺品', '收藏品', '乐器', '书籍',
        '绿植', '装饰品', '工具', '配件'
      ]
    };
    
    const categoryTitles = titles[category] || ['校园闲置物品'];
    const title = categoryTitles[Math.floor(Math.random() * categoryTitles.length)];
    return `${title} #${index}`;
  }
  
  /**
   * 生成商品描述
   */
  private static generateProductDescription(category: ProductCategory): string {
    const descriptions = {
      [ProductCategory.TEXTBOOKS]: [
        '教材保持完好，无涂写痕迹，适合新生使用。',
        '专业课教材，内容详实，重点标注清晰。',
        '经典教材版本，学长学姐推荐，备考必备。'
      ],
      [ProductCategory.ELECTRONICS]: [
        '电子产品保养良好，功能正常，原装配件齐全。',
        '个人自用设备，无维修记录，性能稳定。',
        '国行正品，包装配件完整，支持验货。'
      ],
      [ProductCategory.CLOTHING]: [
        '衣物清洗干净，尺码标准，适合校园日常穿着。',
        '品牌正品，款式经典，保养得当。',
        '季节性闲置，穿着次数不多，保持干净整洁。'
      ],
      default: [
        '校园闲置物品，保持良好状态，价格实惠。',
        '学生自用，品质有保障，欢迎咨询。',
        '毕业闲置，功能完好，支持面交验货。'
      ]
    };
    
    const categoryDescriptions = descriptions[category] || descriptions.default;
    return categoryDescriptions[Math.floor(Math.random() * categoryDescriptions.length)];
  }
  
  /**
   * 计算调整后的价格（根据新旧程度）
   */
  private static calculateAdjustedPrice(basePrice: number, condition: string): number {
    const multipliers = {
      new: 0.9,      // 全新打9折
      like_new: 0.8, // 九成新打8折
      very_good: 0.7, // 八成新打7折
      good: 0.6,     // 七成新打6折
      fair: 0.5,     // 六成新打5折
      poor: 0.3      // 五成新及以下打3折
    };
    
    return Math.round(basePrice * (multipliers[condition] || 0.7));
  }
  
  /**
   * 生成商品图片
   */
  private static generateProductImages(productId: number): Product['images'] {
    const imageCount = Math.floor(Math.random() * 3) + 1;
    const images = [];
    
    for (let i = 1; i <= imageCount; i++) {
      images.push({
        id: `img_${productId}_${i}`,
        url: `https://picsum.photos/600/400?random=${productId * 10 + i}`,
        thumbnailUrl: `https://picsum.photos/300/200?random=${productId * 10 + i}`,
        isCover: i === 1,
        description: `商品图片 ${i}`,
        uploadedAt: new Date()
      });
    }
    
    return images;
  }
  
  /**
   * 生成地理位置信息
   */
  private static generateLocation(): Product['location'] {
    const schools = [
      '清华大学', '北京大学', '复旦大学', '上海交通大学', 
      '浙江大学', '南京大学', '武汉大学', '中山大学'
    ];
    const campuses = ['主校区', '东校区', '西校区', '南校区', '北校区'];
    
    return {
      school: schools[Math.floor(Math.random() * schools.length)],
      campus: campuses[Math.floor(Math.random() * campuses.length)],
      address: '学生宿舍区',
      longitude: 116.3 + Math.random() * 0.5,
      latitude: 39.9 + Math.random() * 0.3
    };
  }
  
  /**
   * 生成发布者信息
   */
  private static generatePublisher(): Product['publisher'] {
    const users = [
      { id: 'user_001', username: '学霸小明', verified: true },
      { id: 'user_002', username: '技术宅小李', verified: true },
      { id: 'user_003', username: '文艺青年小王', verified: true },
      { id: 'user_004', username: '运动达人小张', verified: true },
      { id: 'user_005', username: '生活家小刘', verified: false },
      { id: 'user_006', username: '游戏爱好者小陈', verified: true }
    ];
    
    const user = users[Math.floor(Math.random() * users.length)];
    
    return {
      userId: user.id,
      username: user.username,
      avatar: `https://i.pravatar.cc/150?img=${Math.floor(Math.random() * 70)}`,
      isStudentVerified: user.verified,
      school: '清华大学',
      contactInfo: Math.random() > 0.5 ? {
        wechat: `wx_${user.username}`,
        qq: `${Math.floor(Math.random() * 100000000)}`
      } : undefined
    };
  }
  
  /**
   * 生成随机日期（过去90天内）
   */
  private static generateRandomDate(): Date {
    const now = Date.now();
    const ninetyDaysAgo = now - (90 * 24 * 60 * 60 * 1000);
    return new Date(ninetyDaysAgo + Math.random() * (now - ninetyDaysAgo));
  }
  
  /**
   * 生成商品标签
   */
  private static generateTags(category: ProductCategory): string[] {
    const baseTags = ['校园', '二手', '学生', '实惠'];
    const categoryTags = {
      [ProductCategory.TEXTBOOKS]: ['教材', '学习', '考试'],
      [ProductCategory.ELECTRONICS]: ['数码', '科技', '智能'],
      [ProductCategory.CLOTHING]: ['时尚', '潮流', '品牌'],
      [ProductCategory.DAILY_GOODS]: ['生活', '实用', '家居'],
      [ProductCategory.SPORTS]: ['运动', '健身', '健康'],
      [ProductCategory.STATIONERY]: ['学习', '文具', '办公'],
      [ProductCategory.DORMITORY]: ['宿舍', '住宿', '收纳'],
      [ProductCategory.OTHER]: ['闲置', '创意', '收藏']
    };
    
    return [...baseTags, ...(categoryTags[category] || [])].slice(0, 6);
  }
  
  /**
   * 生成库存数量
   */
  private static generateStock(): number {
    return Math.floor(Math.random() * 3) + 1;
  }
  
  /**
   * 数据清理工具
   */
  static clearMockData(): void {
    this.mockDataStorage.clear();
    console.log('Mock数据已清理');
  }
  
  /**
   * 数据统计工具
   */
  static analyzeMockData(products: Product[]): {
    total: number;
    byCategory: Record<string, number>;
    byStatus: Record<string, number>;
    priceStats: { min: number; max: number; avg: number };
  } {
    const byCategory: Record<string, number> = {};
    const byStatus: Record<string, number> = {};
    let totalPrice = 0;
    let minPrice = Infinity;
    let maxPrice = -Infinity;
    
    products.forEach(product => {
      // 分类统计
      byCategory[product.category] = (byCategory[product.category] || 0) + 1;
      
      // 状态统计
      byStatus[product.status] = (byStatus[product.status] || 0) + 1;
      
      // 价格统计
      totalPrice += product.price;
      minPrice = Math.min(minPrice, product.price);
      maxPrice = Math.max(maxPrice, product.price);
    });
    
    return {
      total: products.length,
      byCategory,
      byStatus,
      priceStats: {
        min: minPrice,
        max: maxPrice,
        avg: Math.round(totalPrice / products.length)
      }
    };
  }
  
  /**
   * 导出Mock数据到JSON文件
   */
  static exportMockData(products: Product[], filename: string = 'mock_products.json'): void {
    const data = {
      generatedAt: new Date().toISOString(),
      totalCount: products.length,
      products: products
    };
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
    
    console.log(`Mock数据已导出到 ${filename}`);
  }
  
  /**
   * 从JSON文件导入Mock数据
   */
  static importMockData(jsonData: string): Product[] {
    try {
      const data = JSON.parse(jsonData);
      if (data.products && Array.isArray(data.products)) {
        console.log(`成功导入 ${data.products.length} 条商品数据`);
        return data.products;
      }
      throw new Error('数据格式错误');
    } catch (error) {
      console.error('导入Mock数据失败:', error);
      return [];
    }
  }
}

/**
 * 开发环境Mock数据调试工具
 */
export class MockDebugUtils {
  /**
   * 在控制台打印Mock数据统计信息
   */
  static logMockStats(products: Product[]): void {
    const stats = MockDataUtils.analyzeMockData(products);
    
    console.group('📊 Mock数据统计信息');
    console.log(`📦 总商品数: ${stats.total}`);
    console.log('🏷️ 分类分布:');
    Object.entries(stats.byCategory).forEach(([category, count]) => {
      console.log(`   ${category}: ${count} (${((count / stats.total) * 100).toFixed(1)}%)`);
    });
    console.log('📈 状态分布:');
    Object.entries(stats.byStatus).forEach(([status, count]) => {
      console.log(`   ${status}: ${count} (${((count / stats.total) * 100).toFixed(1)}%)`);
    });
    console.log('💰 价格统计:');
    console.log(`   最低: ¥${stats.priceStats.min}`);
    console.log(`   最高: ¥${stats.priceStats.max}`);
    console.log(`   平均: ¥${stats.priceStats.avg}`);
    console.groupEnd();
  }
  
  /**
   * 生成Mock数据测试报告
   */
  static generateTestReport(products: Product[]): {
    total: number;
    categories: string[];
    priceRange: string;
    statusCounts: Record<string, number>;
    sampleProducts: Product[];
  } {
    const stats = MockDataUtils.analyzeMockData(products);
    
    return {
      total: products.length,
      categories: Object.keys(stats.byCategory),
      priceRange: `¥${stats.priceStats.min} - ¥${stats.priceStats.max}`,
      statusCounts: stats.byStatus,
      sampleProducts: products.slice(0, 3) // 返回前3个商品作为样本
    };
  }
}

// 默认导出工具类
export default MockDataUtils;